﻿namespace CloudNinja.Metering.Providers.Configuration.DatabaseBandwidth
{
    using System.Configuration;
    using System.Linq;

    using CloudNinja.Metering.Common;
    using CloudNinja.Metering.Common.Configuration;
    using CloudNinja.Metering.Common.Logging;
    using CloudNinja.Metering.Data;
    using CloudNinja.Metering.Providers;

    using Microsoft.Practices.Unity;

    public class DatabaseBandwidthMeteringProviderElement : ProviderElement
    {
        [ConfigurationProperty("DatabaseBandwidthMeteringProviderSettings")]
        public DatabaseBandwidthMeteringProviderSettings DatabaseBandwidthMeteringProviderSettings
        {
            get
            {
                return this["DatabaseBandwidthMeteringProviderSettings"] as DatabaseBandwidthMeteringProviderSettings;
            }

            set
            {
                this["DatabaseBandwidthMeteringProviderSettings"] = value;
            }
        }

        public override void RegisterType(IUnityContainer container, MeteringSection meteringConfiguration)
        {
            var servers = from object databaseSizeMeteringProviderSetting in
                              this.DatabaseBandwidthMeteringProviderSettings.DatabaseServers
                          select databaseSizeMeteringProviderSetting as DatabaseServersCollectionElement;
            var serversDict = servers.ToDictionary(
                setting => setting.Value,
                setting =>
                setting.TenantIdPattern.Equals(string.Empty)
                    ? this.DatabaseBandwidthMeteringProviderSettings.DefaultTenantIdPattern
                    : setting.TenantIdPattern);

            var dbSizeProviderInjectionCtor = new InjectionConstructor(
                this.CollectInterval,
                serversDict,
                container.Resolve<ILogger>(),
                container.Resolve<IMeteringRepository>(),
                container.Resolve<IMeteringContext>());

            container.RegisterType<IMeteringProvider, Providers.SQLAzure.DatabaseBandwidthUsageProvider>(
                typeof(Providers.SQLAzure.DatabaseBandwidthUsageProvider).ToString(),
                new ContainerControlledLifetimeManager(),
                dbSizeProviderInjectionCtor);
        }

        protected override object OnRequiredPropertyNotFound(string name)
        {
            // HACK: Do not really understand why it comes here with these properties, which is clearly defined above.
            return name.Equals("DatabaseBandwidthMeteringProviderSettings") ? null : base.OnRequiredPropertyNotFound(name);
        }
    }
}